<template>
  <el-row class="login-container" justify="center" align="middle">
    <el-card style="max-width: 480px">
      <template #header>
        <div class="card-header">
          <img :src="imgUrl" alt="">
        </div>
        <div class="jump-link">
          <!-- <el-button type="primary" @click="handleChange">{{ formTypeWord }}</el-button> -->
          <div @click="handleChange" type="primary" class="wordType">
            {{ formTypeWord }}
          </div>
          <!-- <el-link type="primary" @click="handleChange">{{ formTypeWord }}</el-link> -->
        </div>
        <el-form :model="loginForm" style="max-width: 400px" class="demo-ruleForm"
        :rules = "rules"
        ref="loginFormRef">
          <el-form-item prop="userName">
            <el-input v-model="loginForm.userName" placeholder="手机号" prefix-icon="UserFilled"></el-input>
          </el-form-item>
          <el-form-item prop="passWord">
            <el-input v-model="loginForm.passWord" type="password" placeholder="密码" prefix-icon="Lock"></el-input>
          </el-form-item>
          <el-form-item prop="validCode" v-if="formType">
            <el-input v-model="loginForm.validCode"  placeholder="验证码" prefix-icon="Lock">
              <template #append>
              <span @click="countDownChange">{{ countDown.validText }}</span>
            </template>
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" :style="{width: '100%'}" @click="submitForm(loginFormRef)">
                  {{ formType ? '注册账号' : '登录' }}
            </el-button>
          </el-form-item>
        </el-form>
      </template>
    </el-card>
  </el-row>
</template>

<script setup>
import {ref, reactive, computed, toRaw} from 'vue'
import {getCode, userAuthentication,login, menuPermissions} from '../../api'
import { UserFilled, Lock } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import {useRouter} from 'vue-router'
import {useStore} from 'vuex'
const imgUrl = new URL('../../../public/login-head.png', import.meta.url).href
const formTypeWord = computed(() => formType.value === 1 ? '返回登录' : '注册账号')

const router = useRouter()
//切换表单(0登录1注册)
const formType = ref(1)


const routerList = computed(() => store.state.menu.routerList)

//表单数据
const loginForm = reactive({
  userName: '',
  passWord: '',
  validCode : ''
})
// 账号校验规则
const validateUser = (rule, value, callback) => {
  //不能为空
  if(value === '') {
    callback(new Error('请输入手机号'))
  }
  else {
    const phoneReg = /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/
    phoneReg.test(value) ? callback() : callback(new Error('手机号格式不对,请输入正确的手机号'))
  }
}
// 密码校验规则
const validatePass = (rule, value, callback) => {
  //不能为空
  if(value === '') {
    callback(new Error('请输入密码'))
  }
  else {
    const passReg = /^[a-zA-Z0-9_-]{4,16}$/
    passReg.test(value) ? callback() : callback(new Error('密码格式不对,需要4到16位字符,请确认格式是否正确'))
  }
}

//表单校验
const rules = reactive({
  userName: [{ validator: validateUser, trigger: 'blur'}],
  passWord: [{ validator: validatePass, trigger: 'blur'}]
})


//点击切换登录和注册
const handleChange = () => {
  formType.value = formType.value === 1 ? 0 : 1
  console.log(formTypeWord.value)
}

//发送短信
const countDown = reactive({
  validText: '获取验证码',
  time: 60
})
//用于记录定时器的状态
let flag = false
const countDownChange = () => {
  if(flag) return 
  //判断手机号是否正确
  const phoneReg = /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/
  if(!loginForm.userName || !phoneReg.test(loginForm.userName)) {
    return ElMessage({
    message: '请检查手机号是否正确',
    type: 'warning',
  })
  }
  const time  = setInterval(() => {
    if(countDown.time <= 0) {
      //进行重置
      countDown.time = 60
      countDown.validText = '获取验证码'
      flag = false
      clearInterval(time)
    }
    else
    {
    //   countDown.time -= 1
    // countDown.validText = `剩余${countDown.time}秒`
    // countDown.validText = `剩余${countDown.time--}秒
  }
  }, 1000)
  flag = true
  getCode({ tel: loginForm.userName }).then(({data}) => {
    console.log(data, 'data');
    if(data.code === 10000) {
      ElMessage.success('发送成功')
      // console.log('发送成功，发送成功')
    }
  })
}
const loginFormRef = ref()
const store = useStore()

//表单提交
const submitForm = async(formEl) => {
  if (!formEl) return
  //进行手动触发表单校验
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log(loginForm, 'submit!')
      //注册页面
      if(formType.value === 1) {
        userAuthentication(loginForm).then(({data}) => {
          if(data.code === 10000) {
            ElMessage.success('注册成功,请登录')
            formType.value = 0
          }
        })
      }
      else{
        login(loginForm).then(({data}) => {
          if(data.code === 10000) {
            ElMessage.success('登录成功')
            console.log(data);
            //将token和用户信息缓存到浏览器
            localStorage.setItem('pz_token', data.data.token)
            localStorage.setItem('pz_userInfo', JSON.stringify(data.data.userInfo))
            menuPermissions().then(({data}) => {
              store.commit('dynamicMenu', data.data)//使用commit来调用store里面的mutations里面的方法
              console.log(routerList, 'routerList');
              toRaw(routerList.value).forEach(item => {
                router.addRoute('main', item)
              })
              router.push('/')
            })
          }
        })
      }
    } else {
      console.log('error submit!', fields)
    }
  })
}
</script>

<style lang="less" scoped>
:deep(.el-card__header) {
    padding: 0
  }
  .login-container {
    height: 100%;
    .card-header{
      background-color: #899fe1;
      img {
        width: 430px;
      }
    }
    .jump-link {
      text-align: right;
      margin-bottom: 10px;
    }
  }
  .demo-ruleForm{
    margin: 0 auto;
  }
  .wordType{
    font-size: 14px;     /* 与输入框字号保持一致 */
    font-weight: 400;    /* 常规字重（非加粗） */
    color: #606266;      /* Element Plus 默认文字灰 */
    padding-top: 5px;
    padding-right: 5px;
    &:hover{
      cursor: default;
    }
  }
</style>